﻿import axios from 'axios'
import VTitle from '@/components/common/MainTitle.vue'
import VSelect from './SelectNo.vue'
export default {
  data () {
    return {
      titleName: '登录账号管理',
      tableData: [],
      tableColumn: [
        {
          text: '登录账号',
          indexName: 'loginid'
        },
        {
          text: '登录名称',
          indexName: 'loginname'
        },
        {
          text: '用户类型',
          indexName: 'usertype'
        },
        {
          text: '用户编号',
          indexName: 'userno'
        },
        {
          text: '手机号码',
          indexName: 'mobile'
        },
        {
          text: 'QQ号码',
          indexName: 'qq'
        }
      ],
      // 编辑和新增的弹窗部分
      dialogTitle: '',
      dialogFormVisible: false,
      // 判断密码是否更改
      loginOldPass: '',
      loginNewPass: '',
      // 角色部分
      roleList: [],
      // 表单规则
      ruleForm: {
        uid: '',
        loginId: '',
        loginName: '',
        loginPass: '',
        userType: '',
        userNo: '',
        userMobile: '',
        userQQ: '',
        role: [],
        avatarUrl: ''
      },
      labelWidth: '94px',
      operationType: '',
      rules: {
        loginId: [
          {required: true, message: '登录账号不能为空', trigger: 'blur'}
        ],
        loginName: [
          {required: true, message: '登录名称不能为空', trigger: 'blur'}
        ],
        loginPass: [
          {required: true, message: '登录密码不能为空', trigger: 'blur'}
        ],
        role: [
          {required: true, message: '请选择角色', trigger: 'change'}
        ],
        userMobile: [
          {pattern: /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/, message: '手机号格式不正确', trigger: 'change'}
        ],
        userQQ: [
          {pattern: /^[1-9][0-9]{4,9}$/, message: 'qq号格式不正确', trigger: 'change'}
        ]
      },
      // 页码部分
      searchKey: '',
      isSearch: false,
      totalData: [],
      filterData: [],
      totalLength: 0,
      currentPage: 1,
      pageSize: 10,
      // 选择编号的部分
      selectType: '',
      showDialog: false,
      // 上传部分
      /* global $URL */
      actionUrl: `${$URL.IMG_UPLOAD_URL}`,
      fileList: [],
      fileReader: '',
      // 用户图片的状态（noAvatar--没有图片， haveAvatar--需要上传图片，deleteAvatar--需要删除图片, haveAvatarAndDelete---先上传后删除）
      avatarFileOptions: 'noAvatar',
      loading: false,
      // 新增或编辑时
      dialogLoading: false
    }
  },
  created () {
    this.getTableData()
    this.getRoles()
  },
  mounted () {
    if (!window.FileReader) {
      this.$message({
        message: '您的浏览器不支持 FileReader API',
        type: 'warning'
      })
    } else {
      this.fileReader = new FileReader()
    }
  },
  methods: {
    // 初始化表格的数据
    getTableData () {
      this.searchKey = ''
      this.loading = true
      this.operationType = ''
      this.$get('/loginuser').then((data) => {
        if (data.status === 200) {
          this.totalData = []
          data.data.result.forEach(item => {
            if (this.$store.state.roleNo && this.$store.state.roleNo.indexOf('R999') !== -1) { // 超级管理员展示所有的
              this.totalData.push(item)
            } else {
              // 不显示超级管理员的账号信息
              let roles = item.roles ? item.roles.join(',') : ''
              if (!roles || roles.indexOf('R999') === -1) {
                this.totalData.push(item)
              }
            }
          })
          this.totalLength = this.totalData.length
          // 调用方法进行页面渲染
          this.showData(this.totalData)
          this.loading = false
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 获取所有的角色
    getRoles () {
      this.$get('/role').then((data) => {
        if (data.status === 200) {
          this.roleList = data.data.result
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 当选择的用户编号时
    selectNo () {
      this.showDialog = true
    },
    // 当选择编号成功时
    sureSelect (fromSelect) {
      this.showDialog = false
      this.ruleForm.userNo = fromSelect.student_no
    },
    // 角色授权
    handleAsign (row) {
      this.dialogFormVisible = true
      this.dialogTitle = '角色授权'
      this.ruleForm.loginId = row.loginid
      this.ruleForm.uid = row.uid
      this.operationType = 'asign'
      this.ruleForm.role = row.roles
    },
    // 添加账号
    handleAdd () {
      this.dialogFormVisible = true
      this.dialogTitle = '添加账号'
      this.ruleForm.uid = ''
      this.ruleForm.loginId = ''
      this.ruleForm.loginName = ''
      this.ruleForm.loginPass = ''
      this.ruleForm.userType = 'System'
      this.ruleForm.userNo = ''
      this.ruleForm.userMobile = ''
      this.ruleForm.userQQ = ''
      this.ruleForm.avatarUrl = ''
      this.fileList = []
      this.avatarFileOptions = 'noAvatar'
      this.operationType = 'add'
    },
    // 编辑账号
    handleEdit (row) {
      this.dialogFormVisible = true
      this.dialogTitle = '编辑账号信息'
      this.ruleForm.uid = row.uid
      this.ruleForm.loginId = row.loginid
      this.ruleForm.loginName = row.loginname
      this.ruleForm.loginPass = row.loginpass
      this.ruleForm.userType = row.usertype
      this.ruleForm.userNo = row.userno
      this.loginOldPass = row.loginpass
      this.ruleForm.userMobile = row.mobile
      this.ruleForm.userQQ = row.qq
      this.ruleForm.avatarUrl = row.avatar
      this.fileList = []
      // 当有图像已经上传时，需要展示出来
      if (this.ruleForm.avatarUrl) {
        let obj = {
          linkUrl: this.ruleForm.avatarUrl,
          url: this.ruleForm.avatarUrl.indexOf('/dl/') !== -1 ? this.ruleForm.avatarUrl.replace('/dl/', '/') : this.ruleForm.avatarUrl,
          status: 'success'
        }
        this.fileList.push(obj)
      }
      this.avatarFileOptions = 'noAvatar'
      this.operationType = 'edit'
    },
    // 删除账号信息
    handleDelete (row) {
      this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.$delete('/loginuser/' + row.uid).then((data) => {
          if (data.status === 204) {
            if (row.avatar) {
              // 删除成功时，如果有用户图片，需要将图片删除
              this.removeAvatarMethod(row.avatar, 'delete')
            } else {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getTableData()
            }
          }
        }).catch((error) => {
          if (error.response.status === 404) {
            this.$message.error('删除失败，请重试！')
          }
        })
      }).catch(() => {})
    },
    // 编辑的方法
    editFunc (avatarUrl) {
      // 首先判断是否更改密码
      if (this.ruleForm.loginPass === this.loginOldPass) {
        this.loginNewPass = ''
      } else {
        this.loginNewPass = this.ruleForm.loginPass
      }
      this.$patch('/loginuser/' + this.ruleForm.uid, {
        loginid: this.ruleForm.loginId,
        loginname: this.ruleForm.loginName,
        old_loginpass: this.loginOldPass,
        loginpass: this.loginNewPass,
        usertype: this.ruleForm.userType,
        userno: this.ruleForm.userNo,
        mobile: this.ruleForm.userMobile,
        qq: this.ruleForm.userQQ,
        avatar: avatarUrl
      }).then((data) => {
        if (data.data.result.code === 'success') {
          this.dialogFormVisible = false
          this.$message({
            message: '编辑成功',
            type: 'success'
          })
          this.getTableData()
        } else {
          this.$message.error(data.data.result.msg)
        }
        this.dialogLoading = false
      }).catch((error) => {
        console.log(error)
      })
    },
    // 新增的方法
    addFunc (avatarUrl) {
      this.$post('/loginuser', {
        loginid: this.ruleForm.loginId,
        loginname: this.ruleForm.loginName,
        loginpass: this.ruleForm.loginPass,
        usertype: this.ruleForm.userType,
        userno: this.ruleForm.userNo,
        mobile: this.ruleForm.userMobile,
        qq: this.ruleForm.userQQ,
        avatar: avatarUrl
      }).then((data) => {
        if (data.data.result.code === 'success') {
          this.dialogFormVisible = false
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.getTableData()
        } else {
          this.$message.error(data.data.result.msg)
        }
        this.dialogLoading = false
      }).catch((error) => {
        console.log(error)
      })
    },
    // 提交角色授权的方法
    submitAsign () {
      this.$post('/roleauth/role2login', {
        loginuid: this.ruleForm.uid,
        roleno: this.ruleForm.role.join()
      }).then((data) => {
        if (data.data.result.code === 'success') {
          this.dialogFormVisible = false
          this.$message({
            message: '角色授权成功',
            type: 'success'
          })
          this.getTableData()
        } else {
          this.$message.error(data.data.result.msg)
        }
        this.dialogLoading = false
      }).catch((error) => {
        console.log(error)
      })
    },
    // 文件超过最大上传个数时
    onExceed () {
      this.$message({
        message: '一次只能上传一个图片，请先移除文件列表中的图片，再选择需要上传的图片',
        type: 'warning',
        duration: 5000
      })
    },
    // 上传文件改变
    changeAvatarUpload () {
      // 新增时使用，判断提交时，是否需要先上传文件
      if (this.ruleForm.avatarUrl) {
        this.avatarFileOptions = 'haveAvatarAndDelete'
      } else {
        this.avatarFileOptions = 'haveAvatar'
      }
    },
    // 上传文件移除
    removeUpload (file) {
      // 编辑时使用
      // 文件已经上传时
      if (file.status === 'success' && file.linkUrl) {
        this.avatarFileOptions = 'deleteAvatar'
      } else {
        // 文件没有上传时
        this.avatarFileOptions = 'noAvatar'
      }
    },
    // 上传用户图片的方法
    uploadUserAvatarMethod (options) {
      let file = options.file
      let filename = file.name
      let fileLength = file.size
      if (file) {
        this.fileReader.readAsDataURL(file)
      }
      this.fileReader.onload = () => {
        let base64Str = this.fileReader.result
        /* global $URL */
        axios({
          url: $URL.IMG_UPLOAD_URL + '/fileset/upload',
          method: 'post',
          data: {
            file_name: filename,
            file_length: fileLength,
            file_content: base64Str.split(',')[1]
          }
        }).then(data => {
          let dataResult = data.data.result
          if (dataResult.code === 'success') {
            // 上传成功后，根据operationType来判断是执行编辑还是新增的方法
            if (this.operationType === 'edit') {
              this.editFunc(dataResult.link_url)
            } else if (this.operationType === 'add') {
              this.addFunc(dataResult.link_url)
            }
          } else {
            this.$message({
              message: dataResult.msg,
              type: 'error',
              duration: 5000
            })
          }
        }).catch(error => {
          console.log(error)
        })
      }
    },
    // 移除用户图片的方法
    removeAvatarMethod (downUrl, type) {
      // 删除文件的方法
      if (!downUrl) {
        return
      }
      downUrl = downUrl.replace('/fileset/dl/', '/fileset/recycle/')
      axios({
        url: downUrl,
        method: 'patch'
      }).then(data => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          if (type === 'edit') {
            this.ruleForm.avatarUrl = ''
            // 执行编辑的方法
            this.editFunc(this.ruleForm.avatarUrl)
          } else if (type === 'delete') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getTableData()
          } else if (type === 'editAndDelete') {
            this.ruleForm.avatarUrl = ''
            // 删除完成后，执行上传的方法
            this.$refs.upload.submit()
          }
        } else {
          this.$message({
            message: dataResult.msg,
            type: 'error',
            duration: 5000
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 点击弹窗的确定按钮
    submitForm (forms, submitType) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          this.dialogLoading = true
          if (submitType === 'edit') {
            if (this.avatarFileOptions === 'haveAvatar') {
              // 有需要上传的图片时
              this.$refs.upload.submit()
            } else if (this.avatarFileOptions === 'deleteAvatar') {
              // 有上传的图片删除时，需要先删除图片
              this.removeAvatarMethod(this.ruleForm.avatarUrl, 'edit')
            } else if (this.avatarFileOptions === 'haveAvatarAndDelete') {
              // 跟换图片时，需要先删除，再上传，在提交编辑
              this.removeAvatarMethod(this.ruleForm.avatarUrl, 'editAndDelete')
            } else {
              // 直接执行编辑的方法
              this.editFunc(this.ruleForm.avatarUrl)
            }
          } else if (submitType === 'add') {
            if (this.avatarFileOptions === 'haveAvatar') {
              this.$refs.upload.submit()
            } else {
              this.addFunc('')
            }
          } else if (submitType === 'asign') {
            this.submitAsign()
          }
        } else {
          return false
        }
      })
    },
    // 点击弹窗的取消按钮
    resetForm (forms) {
      this.$refs[forms].clearValidate()
      this.dialogFormVisible = false
    },
    closeDialog () {
      this.$refs.ruleForm.clearValidate()
    },
    // 将页码与数据关联
    showData (myData) {
      // 渲染表格的数据存放在 this.tableData 中
      this.tableData = []
      if (myData.length) {
        let from = (this.currentPage - 1) * this.pageSize
        let to = this.currentPage * this.pageSize
        if (to > myData.length) {
          to = myData.length
        }
        for (; from < to; from++) {
          this.tableData.push(myData[from])
        }
      }
    },
    // 底部页码的部分
    handleSizeChange (val) {
      this.pageSize = val
      // 需要判断是否是检索的数据
      if (this.isSearch) {
        this.showData(this.filterData)
      } else {
        this.showData(this.totalData)
      }
    },
    handleCurrentChange (val) {
      this.currentPage = val
      // 需要判断是否是检索的数据
      if (this.isSearch) {
        this.showData(this.filterData)
      } else {
        this.showData(this.totalData)
      }
    }
  },
  watch: {
    // 搜索的功能
    searchKey: {
      handler: function (val, oldVal) {
        // 当检索的内容为空时需要将表格的内容还原
        if (this.$trim(val) === '') {
          this.pageSize = 10
          this.currentPage = 1
          this.totalLength = this.totalData.length
          this.isSearch = false
          // 调用方法进行页面渲染
          this.showData(this.totalData)
        } else {
          // 检索结果的数据存放在 this.filterData 中
          this.filterData = []
          this.totalData.forEach((value, index) => {
            if (value.loginid) {
              if (value.loginid.indexOf(this.searchKey) >= 0) {
                this.filterData.push(value)
              }
            }
          })
          this.isSearch = true
          this.currentPage = 1
          this.totalLength = this.filterData.length
          // 调用方法进行页面渲染
          this.showData(this.filterData)
        }
      },
      deep: true
    }
  },
  components: {
    VTitle,
    VSelect
  }
}
